# -*- coding: utf-8 -*-
import os
import time
import xlrd
import xlsxwriter
from flask import Flask, render_template, request, send_from_directory, jsonify
import csv
import random
from db_operate import *


reload(sys)
sys.setdefaultencoding('utf8')

cfg = ConfigParser.ConfigParser()
cfg.read('conf/config.txt')

STATUS_URL = cfg.get('default', 'status_url')
PROJECT_URL = cfg.get('default', 'project_url')
DATAPROCESS_URL = cfg.get('default', 'dataprocess_url')
DOWNLOAD_URL = cfg.get('default', 'download_dir')
FILE_SERVER = cfg.get('default', 'file_server')
SAVE_DIR = cfg.get('default', 'save_dir')
CUSTOMQQ_URL = cfg.get('default', 'customqq_url')
RECOMMEND_URL = cfg.get('default', 'recommend_url')
DATABASE_URL = cfg.get('default', 'database_url')

MAX_ROWS = 65536
ERROR_SUCCESS = 'OK'
ERROR_PARTIAL = 'PARTIAL'

userid = 0

UPLOAD_FOLDER = cfg.get('default', 'upload_dir')
ALLOWED_EXTENSIONS = set(['xlsx'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


def open_excel(filename='file.xls'):
    data = xlrd.open_workbook(filename)
    return data


@app.route('/', methods=['GET', 'POST'])
def index():
    payload = {'mode': 'full'}
    project_names = list()
    try:
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key('status') and jdata.get('status') is False:
            pass
        else:
            project_names = jdata.keys()
    except requests.ConnectionError:
        return '请求url: %s 连接异常' % PROJECT_URL
    return render_template('index.html', appids=['test', 'test_lijinyu', 'test_li'])


@app.route('/download', methods=['GET', 'POST'])
def download():
    payload = {'mode': 'full'}
    project_names = list()
    try:
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key('status') and jdata.get('status') is False:
            pass
        else:
            project_names = jdata.keys()
    except requests.ConnectionError:
        return '请求url: %s 连接异常' % PROJECT_URL
    return render_template('download.html', appids=['test'])


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        form_data = request.form
        appid = form_data.get('appid', '')
        # appid = 'appid'
        updatemode = form_data.get('updatemode', '')
        datatype = form_data.get('datatype', '')
        response_dict = {'status': 'false', 'desc': ''}
        try:
            file = request.files['filename']
            if not allowed_file(file.filename):
                response_dict['desc'] = '目前只支持上传xlsx的文件格式'
                return jsonify(response_dict)
            filename = file.filename
            new_filename = filename.rsplit('.')[0] + time.strftime('_%m%d%H%M%S', time.localtime()) + '.xlsx'
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))

            workbook = open_excel(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
            read_table = workbook.sheets()[3]
            # 获取总行数
            total_rows = read_table.nrows
            total_cols = read_table.ncols
            if total_rows > MAX_ROWS:
                response_dict['desc'] = '文件行数过多，最多支持文件行数为：%s' % MAX_ROWS
                return jsonify(response_dict)

            entities = list()
            question_list = list()
            error_list = list()
            if datatype == 'SQ-Answer':
                for row in range(1, total_rows):
                    answers = list()
                    entity_dict = dict()
                    question = read_table.cell(row, 0).value
                    if question == '':
                        continue
                    elif question in question_list:
                        error_list.append(row + 1)
                        continue
                    else:
                        question_list.append(question)
                        entity_dict['content'] = question

                    for col in range(1, total_cols):
                        answer = read_table.cell(row, col).value
                        if answer:
                            answers.append(answer)
                    entity_dict['answers'] = answers
                    entities.append(entity_dict)

                if len(error_list):
                    response_dict['desc'] = '行 %s 发现重复数据，请检查后重新上传' % error_list
                    return jsonify(response_dict)

                result_dict = insert_questions('sq', appid, 0, entities)

                record_dict = result_dict.get('data')
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                else:
                    response_dict['desc'] = '导入成功'

                # 默认插入BQ-SQ,此时BQ跟SQ一样
                entities = list()
                for q in record_dict.keys():
                    entity_dict = {'content': q, 'parentRecordId': int(record_dict.get(q))}
                    entities.append(entity_dict)

                result_dict = insert_questions('bq', appid, 0, entities)

            elif datatype == 'SQ-NoAnswer':
                question_list = list()
                for row in range(1, total_rows):
                    question = read_table.cell(row, 0).value
                    # print question
                    if question == '':
                        continue
                    elif question in question_list:
                        error_list.append(row + 1)
                        continue
                    else:
                        question_list.append(question)
                        entity_dict = {'content': question, 'answers': [question]}
                        entities.append(entity_dict)

                if len(error_list):
                    response_dict['desc'] = '行 %s 发现重复数据，请检查后重新上传' % error_list
                    return jsonify(response_dict)

                result_dict = insert_questions('sq', appid, userid, entities)

                record_dict = result_dict.get('data')
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                else:
                    response_dict['desc'] = '导入成功'
                # 默认插入BQ-SQ,此时BQ跟SQ一样
                entities = list()
                for q in record_dict.keys():
                    entity_dict = {'content': q, 'parentRecordId': int(record_dict.get(q))}
                    entities.append(entity_dict)
                print json.dumps(entities, ensure_ascii=False, indent=4)
                result_dict = insert_questions('bq', appid, userid, entities)

            elif datatype == 'BQ-SQ':
                standq_list = list()
                qq_pairs = list()
                for row in range(1, total_rows):
                    bound_q = read_table.cell(row, 0).value
                    stand_q = read_table.cell(row, 1).value
                    if stand_q and stand_q not in standq_list:
                        standq_list.append(stand_q)

                    if bound_q == '' or stand_q == '':
                        continue
                    elif bound_q in question_list:
                        error_list.append(row + 1)
                        continue
                    else:
                        question_list.append(bound_q)
                        qq_pairs.append({'bq': bound_q, 'sq': stand_q})
                    # entities.append(entity_dict)
                if len(error_list):
                    response_dict['desc'] = '行 %s 发现重复数据，请检查后重新上传' % error_list
                    return jsonify(response_dict)

                result_dict = query_default('sq', appid, userid, standq_list)
                record_dict = result_dict.get('data')
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                    return jsonify(response_dict)

                for qq in qq_pairs:
                    bq = qq['bq']
                    sq = qq['sq']
                    entities.append({'content': bq, 'parentRecordId': int(record_dict.get(sq))})

                # 插入BQ-SQ
                result_dict = insert_questions('bq', appid, userid, entities)
                response_dict['status'] = 'true'
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                else:
                    response_dict['desc'] = '导入成功'

            elif datatype == 'LQ-BQ':
                boundq_list = list()
                qq_pairs = list()
                for row in range(1, total_rows):
                    log_q = read_table.cell(row, 0).value
                    bound_q = read_table.cell(row, 1).value

                    if bound_q and bound_q not in boundq_list:
                        boundq_list.append(bound_q)

                    if log_q == '' or bound_q == '':
                        continue
                    elif log_q in question_list:
                        error_list.append(row + 1)
                        continue
                    else:
                        question_list.append(log_q)
                        qq_pairs.append({'lq': log_q, 'bq': bound_q})

                if len(error_list):
                    response_dict['desc'] = '行 %s 发现重复数据，请检查后重新上传' % error_list
                    return jsonify(response_dict)

                result_dict = query_default('bq', appid, userid, boundq_list)
                record_dict = result_dict.get('data')
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                    return jsonify(response_dict)

                for qq in qq_pairs:
                    lq = qq['lq']
                    bq = qq['bq']
                    entities.append({'content': lq, 'parentRecordId': int(record_dict.get(bq))})

                # 插入LQ-BQ
                result_dict = insert_questions('lq', appid, userid, entities)
                response_dict['status'] = 'true'
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                else:
                    response_dict['desc'] = '导入成功'

            elif datatype == 'EQ-BQ':
                boundq_list = list()
                qq_pairs = list()
                for row in range(1, total_rows):
                    edit_q = read_table.cell(row, 0).value
                    bound_q = read_table.cell(row, 1).value

                    if bound_q and bound_q not in boundq_list:
                        boundq_list.append(bound_q)

                    if edit_q == '' or bound_q == '':
                        continue
                    elif edit_q in question_list:
                        error_list.append(row + 1)
                        continue
                    else:
                        question_list.append(edit_q)
                        qq_pairs.append({'eq': edit_q, 'bq': bound_q})

                if len(error_list):
                    response_dict['desc'] = '行 %s 发现重复数据，请检查后重新上传' % error_list
                    return jsonify(response_dict)

                result_dict = query_default('bq', appid, userid, boundq_list)
                record_dict = result_dict.get('data')
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                    return jsonify(response_dict)

                for qq in qq_pairs:
                    eq = qq['eq']
                    bq = qq['bq']
                    entities.append({'content': eq, 'parentRecordId': int(record_dict.get(bq))})

                # 插入EQ-BQ
                result_dict = insert_questions('eq', appid, userid, entities)
                response_dict['status'] = 'true'
                if result_dict.get('desc') != '':
                    response_dict['desc'] = result_dict.get('desc')
                else:
                    response_dict['desc'] = '导入成功'

        except Exception, e:
            response_dict['desc'] = str(e)
        return jsonify(response_dict)


@app.route('/downloadfile', methods=['GET', 'POST'])
def download_file():
    if request.method == 'GET':
        appid = request.args.get('appid')
        payload = {'appid': appid}
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key(appid):
            version = jdata.get(appid)
            file_server_url = os.path.join(FILE_SERVER, appid, version, 'full_data.xlsx')
            r = requests.get(file_server_url)
            new_filename = appid + time.strftime('_%m%d%H%M%S', time.localtime()) + '.xlsx'
            with open(os.path.join(DOWNLOAD_URL, new_filename), 'wb') as xlsx_file:
                xlsx_file.write(r.content)

        else:
            return '请选择正确的项目名称'
        return send_from_directory(DOWNLOAD_URL, new_filename, as_attachment=True)


@app.route('/expand', methods=['GET', 'POST'])
def expand():
    payload = {'mode': 'full'}
    project_names = list()
    try:
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key('status') and jdata.get('status') is False:
            pass
        else:
            project_names = jdata.keys()
    except requests.ConnectionError:
        return '请求url: %s 连接异常' % PROJECT_URL
    return render_template('expand.html', appids=['test', 'test_lijinyu', 'test_li'])


@app.route('/standard', methods=['GET', 'POST'])
def standard_label():
    payload = {'mode': 'full'}
    project_names = list()
    try:
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key('status') and jdata.get('status') is False:
            pass
        else:
            project_names = jdata.keys()
    except requests.ConnectionError:
        return '请求url: %s 连接异常' % PROJECT_URL
    return render_template('standard.html', appids=['test', 'guanzhi'])


@app.route('/label', methods=['GET', 'POST'])
def log_label():
    payload = {'mode': 'full'}
    project_names = list()
    try:
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        if jdata.has_key('status') and jdata.get('status') is False:
            pass
        else:
            project_names = jdata.keys()
    except requests.ConnectionError:
        return '请求url: %s 连接异常' % PROJECT_URL
    return render_template('loglabel.html', appids=['test', 'test_lijinyu'])


@app.route('/getdata', methods=['GET', 'POST', 'OPTIONS'])
def get_data():
    try:
        data_type = request.args.get('type')
        data = list()
        if data_type == 'sq':
            data.append({'standQ': '', 'number': ''})
        elif data_type == 'bq':
            data.append({'boundQ': ''})
        elif data_type == 'eq':
            data.append({'class': '', 'editQ': ''})
        elif data_type == 'empty':
            data.append({'recommendQ': 'Empty', 'boundQ': 'Empty'})
        return jsonify(data)
    except Exception, e:
        print str(e)


@app.route('/fileupload', methods=['GET', 'POST'])
def file_upload():
    if request.method == 'POST':
        file = request.files['edToUpload']
        form_data = request.form
        appid = form_data.get('appid', '')
        response_dict = {'status': 'false', 'logQ': [], 'boundQ': [], 'desc': ''}
        if not allowed_file(file.filename):
            response_dict['desc'] = '目前只支持上传xlsx, xls的文件格式'
            return jsonify(response_dict)
        filename = file.filename
        new_filename = filename.rsplit('.')[0] + time.strftime('_%m%d%H%M%S', time.localtime()) + '.' + \
                       filename.rsplit('.')[1]
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
        workbook = open_excel(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
        read_table = workbook.sheets()[0]
        # 获取总行数
        total_rows = read_table.nrows
        user_questions = list()
        for row in range(1, total_rows):
            question = read_table.cell(row, 0).value
            if question:
                user_questions.append(question)
        if not len(question):
            response_dict['desc'] = '上传文件中的用户问题为空'
            return jsonify(response_dict)
        response_dict['logQ'] = user_questions

        # 根据appid查询所有boundQ
        response_dict['boundQ'] = [{'boundQ': '备胎的尺寸'}, {'boundQ': '外后视镜是否可以手动折叠'},
                                   {'boundQ': '2017留资推荐购潜客的奖励'}, {'boundQ': '云推荐审核未通过原因'},
                                   {'boundQ': '推荐购审核失败怎么办'}, {'boundQ': '激活观致逸云账号的好处'},
                                   {'boundQ': '税末感恩活动内容'}, {'boundQ': '观致使用的发动机和变速箱产地'},
                                   {'boundQ': '观致汽车保养的内容和项目'}, {'boundQ': '如何查看车辆质保期'},
                                   {'boundQ': '如何预约保养'}, {'boundQ': '是否标配发动机防尘盖发动机隔音棉观致3观致5分别回答'},
                                   {'boundQ': '车型对比'}, {'boundQ': '一重礼获取条件'},
                                   {'boundQ': '品牌公司介绍'}, {'boundQ': '可以采纳我的建议吗'},
                                   {'boundQ': '空调自动关闭的情况'}, {'boundQ': '哪些车型可以延保'},
                                   {'boundQ': '你好谢谢再见'}, {'boundQ': '如何查看车架号Vin码'},
                                   {'boundQ': '为什么需要建立个人账号'}, {'boundQ': '无法关闭发动机罩'},
                                   {'boundQ': '价格可以再优惠吗'}, {'boundQ': '车辆无法连接蓝牙'},
                                   {'boundQ': '如何登陆观致逸云账号'}, {'boundQ': '是否要改款改款时间'},
                                   {'boundQ': '观致逸云是什么'}, {'boundQ': '如何拆下观致汽车后排座椅头枕'}]
        response_dict['status'] = 'true'
        return jsonify(response_dict)


@app.route('/getlog', methods=['GET', 'POST'])
def get_userlog():
    if request.method == 'GET':
        data_type = request.args.get('type')
        appid = request.args.get('appid')
        response_dict = {'status': 'false', 'logQ': [], 'boundQ': [], 'desc': ''}
        user_questions = ['60分钟，30分钟，15分钟周期k线没办法复权', '60分钟周期k线没办法复权.',
                          'k线15分钟线为什么不能除权', 'K线不能向前复权怎么办',
                          'K线除权后没有反应', 'K线的复权和除权都没有用',
                          'k线的向前复权和向后复权都不能使用了', 'K线复权操作失败',
                          'K线图的复权除权功能总是出问题', 'k线图为什么不能除权啊',
                          'k线图形无法成功向前复权，点了功能菜单里的选项没有用', '查看k线时，没有前复权后复权选项，希望改进',
                          '点了K线的除权按钮也没用', '股票k线怎么不能复权，新下载的软件还是不能复权',
                          'k线显示复权与除权没有反应', '有些股票k线图不能向前复权',
                          '怎么k线不能复权', '最近使用k线图的复权功能经常出现问题',
                          'k线比例应该可以自由设置', 'K线的大小尺寸建议可以修改']
        response_dict['logQ'] = user_questions

        # 根据appid查询所有boundQ
        response_dict['boundQ'] = [{'boundQ': '备胎的尺寸'}, {'boundQ': '外后视镜是否可以手动折叠'},
                                   {'boundQ': '2017留资推荐购潜客的奖励'}, {'boundQ': '云推荐审核未通过原因'},
                                   {'boundQ': '推荐购审核失败怎么办'}, {'boundQ': '激活观致逸云账号的好处'},
                                   {'boundQ': '税末感恩活动内容'}, {'boundQ': '观致使用的发动机和变速箱产地'},
                                   {'boundQ': '观致汽车保养的内容和项目'}, {'boundQ': '如何查看车辆质保期'},
                                   {'boundQ': '如何预约保养'}, {'boundQ': '是否标配发动机防尘盖发动机隔音棉观致3观致5分别回答'},
                                   {'boundQ': '车型对比'}, {'boundQ': '一重礼获取条件'},
                                   {'boundQ': '品牌公司介绍'}, {'boundQ': '可以采纳我的建议吗'},
                                   {'boundQ': '空调自动关闭的情况'}, {'boundQ': '哪些车型可以延保'},
                                   {'boundQ': '你好谢谢再见'}, {'boundQ': '如何查看车架号Vin码'},
                                   {'boundQ': '为什么需要建立个人账号'}, {'boundQ': '无法关闭发动机罩'},
                                   {'boundQ': '价格可以再优惠吗'}, {'boundQ': '车辆无法连接蓝牙'},
                                   {'boundQ': '如何登陆观致逸云账号'}, {'boundQ': '是否要改款改款时间'},
                                   {'boundQ': '观致逸云是什么'}, {'boundQ': '如何拆下观致汽车后排座椅头枕'}]
        response_dict['status'] = 'true'
        return jsonify(response_dict)


@app.route('/question', methods=['GET', 'POST'])
def get_questions():
    if request.method == 'GET':
        appid = request.args.get('project')
        payload = {'appid': appid}
        r = requests.get(PROJECT_URL, params=payload)
        jdata = r.json()
        response_dict = {'status': 'false'}
        if jdata.has_key('status') and jdata.get('status') is False:
            response_dict['question'] = list()
            return jsonify(response_dict)

        questions = list()
        # 获取版本号目录
        version = jdata.get(appid)

        # 判断文件是否存在
        if not os.path.exists(os.path.join(SAVE_DIR, appid, version, 'question_label_to_answers.csv')):
            response_dict['desc'] = '文件：%s 不存在' % os.path.join(SAVE_DIR, appid, version, 'question_label_to_answers.csv')
            return jsonify(response_dict)

        fp = open(os.path.join(SAVE_DIR, appid, version, 'question_label_to_answers.csv'), 'rb')
        reader = csv.reader(fp)
        for row in reader:
            if row[1]:
                questions.append(row[1])

        # 去除CSV的标题
        if len(questions):
            questions.pop(0)

        response_dict['status'] = 'true'
        response_dict['question'] = questions
        return jsonify(response_dict)


@app.route('/match', methods=['GET', 'POST'])
def match():
    if request.method == 'GET':
        user_q = request.args.get('question')
        appid = request.args.get('project')
        match_q_list = list()
        match_questions = list()
        try:
            payload = {'robot': appid,
                       'UniqueID': random.randint(10000000, 99999999),
                       'UserID': 'abcd',
                       'module_type': 'enable',
                       'module_list': 'faq',
                       'topN': 30,
                       'Text1': user_q
                       }
            r = requests.get(CUSTOMQQ_URL, params=payload)
            jdata = r.json()
            resources = jdata.get('faq').get('res')
            if len(resources):
                for res in resources:
                    match_question = dict()
                    match_question['answer'] = res.get('answer')
                    match_question['score'] = res.get('score')
                    match_q_list.append(match_question)

                # 按照分数进行排序
                match_q_list.sort(key=lambda question: question['score'], reverse=True)

                answer_set = set()
                for answer in match_q_list:
                    if answer['answer'] not in answer_set:
                        match_questions.append(answer['answer'])
                        answer_set.add(answer['answer'])

                    if len(match_questions) == 5:
                        break

            response_dict = {'status': 'true', 'data': match_questions, 'desc': 'success'}
        except Exception, e:
            response_dict = {'status': 'false', 'data': match_questions, 'desc': str(e)}
        return jsonify(response_dict)


@app.route('/save', methods=['GET', 'POST'])
def save_file():
    if request.method == 'POST':
        response_dict = {'status': 'false'}
        try:
            jdata = request.json
            upload_datas = jdata.get('data')
            project_name = jdata.get('project')
            if not project_name:
                response_dict['desc'] = '请选择项目名称'
                return jsonify(response_dict)

            if not upload_datas or not len(upload_datas):
                response_dict['desc'] = '上传数据为空'
                return jsonify(response_dict)

            save_file = project_name + time.strftime('_%m%d%H%M%S', time.localtime()) + '.xlsx'
            if not os.path.exists(os.path.join(SAVE_DIR, project_name)):
                os.mkdir(os.path.join(SAVE_DIR, project_name))
            writebook = xlsxwriter.Workbook(os.path.join(SAVE_DIR, project_name, save_file))
            sheet = writebook.add_worksheet()
            # 添加标题
            titles = [u'用户问题', u'标注答案']
            # 设置数据表格的列名
            for index, title in enumerate(titles):
                sheet.write(0, index, title)
            # 设置列宽
            sheet.set_column('A:B', 20)
            row = 1
            for data in upload_datas:
                sheet.write(row, 0, data.get('Question', ''))
                sheet.write(row, 1, data.get('Answer', ''))
                row += 1
            writebook.close()
            response_dict['status'] = 'true'
            path = os.path.join(FILE_SERVER, project_name, save_file)
            file_path = '<a href="%s">点击下载文件</a>' % path
            response_dict['desc'] = '文件导入成功，%s' % file_path
        except Exception, e:
            response_dict['desc'] = str(e)

        return jsonify(response_dict)


@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == 'GET':
        user_q = request.args.get('question')
        appid = request.args.get('project')
        match_questions = list()
        try:
            payload = {'appid': appid,
                       'seeds': [user_q]
                       }
            r = requests.post(RECOMMEND_URL, data=json.dumps(payload))
            jdata = r.json()
            if jdata.get('error') == '0':
                match_questions = jdata.get('results')

            response_dict = {'status': 'true', 'data': match_questions, 'desc': 'success'}
        except Exception, e:
            response_dict = {'status': 'false', 'data': match_questions, 'desc': str(e)}
        return jsonify(response_dict)


@app.route('/getquestion', methods=['GET', 'POST'])
def get_question():
    if request.method == 'GET':
        response_dict = {'status': 'false', 'data': [], 'desc': ''}
        try:
            data_type = request.args.get('type')
            appid = request.args.get('appid')
            if data_type == 'sq':
                result_dict = query_conditions(data_type, appid, 0)
                record_dict = result_dict['data']
                if record_dict == {}:
                    response_dict['desc'] = '查询数据为空'
                    return jsonify(response_dict)

                query_data = list()
                for index, record in enumerate(record_dict.keys()):
                    record_id = record_dict.get(record)
                    content = record
                    data = {'number': str(index+1), 'id': record_id, 'standQ': content}
                    query_data.append(data)
                response_dict['status'] = 'true'
                response_dict['data'] = query_data
            elif data_type == 'bq':
                parent_id = request.args.get('parentId')
                result_dict = query_conditions(data_type, appid, 0, {'parentRecordId': int(parent_id)})
                if result_dict['status'] == 'false':
                    response_dict['desc'] = '查询数据失败'
                    return jsonify(response_dict)

                record_dict = result_dict['data']
                query_data = list()
                for record in record_dict.keys():
                    record_id = record_dict.get(record)
                    content = record
                    data = {'id': record_id, 'boundQ': content}
                    query_data.append(data)
                response_dict['status'] = 'true'
                response_dict['data'] = query_data
            elif data_type == 'eq':
                parent_id = request.args.get('parentId')
                result_dict = query_conditions(data_type, appid, 0, {'parentRecordId': int(parent_id)})

                record_dict = result_dict['data']
                query_data = list()
                for record in record_dict.keys():
                    record_id = record_dict.get(record)
                    content = record
                    data = {'id': record_id, 'class': 'EQ', 'editQ': content}
                    query_data.append(data)

                # 查询LQ:
                result_dict = query_conditions('lq', appid, 0, {'parentRecordId': int(parent_id)})
                record_dict = result_dict['data']
                for record in record_dict.keys():
                    record_id = record_dict.get(record)
                    content = record
                    data = {'id': record_id, 'class': 'LQ', 'editQ': content}
                    query_data.append(data)

                response_dict['status'] = 'true'
                response_dict['data'] = query_data
        except Exception, e:
            response_dict['desc'] = str(e)

        return jsonify(response_dict)


@app.route('/modifyquestion', methods=['GET', 'POST'])
def modify_question():
    if request.method == 'GET':
        response_dict = {'status': 'false'}
        try:
            old_question = request.args.get('oldValue')
            new_question = request.args.get('newValue')
            data_type = request.args.get('type')
            response_dict['desc'] = '更新成功'
            print old_question, new_question
        except Exception, e:
            response_dict['desc'] = str(e)
        return jsonify(response_dict)


@app.route('/addquestion', methods=['GET', 'POST'])
def add_question():
    if request.method == 'POST':
        response_dict = {'status': 'false', 'desc': ''}
        try:
            jdata = request.json
            add_question = jdata.get('addValue')
            appid = jdata.get('appid')

            entities = list()
            entity = dict()
            print add_question
            data_type = jdata.get('type')
            if data_type == 'sq':
                answers = jdata.get('answers')
                entity['content'] = add_question[0]
                entity['answers'] = answers
                entities.append(entity)

                result_dict = insert_questions(data_type, appid, userid, entities)
                record_dict = result_dict.get('data')
                invalid_dict = result_dict.get('invalid')
                if invalid_dict != {}:
                    response_dict['desc'] = 'SQ: "%s" 已经存在，新增失败' % add_question[0]
                    return jsonify(response_dict)

                response_dict['status'] = 'true'
                record_list = list()
                for record in record_dict.keys():
                    tmp_dict = {'content': record, 'recordId': record_dict.get(record)}
                    record_list.append(tmp_dict)
                response_dict['data'] = record_list

                record_dict2 = insert_questions('bq', appid, userid, [
                    {'content': add_question[0], 'parentRecordId': int(record_dict.get(add_question[0]))}])

            elif data_type == 'bq':
                parentId = jdata.get('parentId')
                for q in add_question:
                    entities.append({'content': q, 'parentRecordId': parentId})

                result_dict = insert_questions(data_type, appid, userid, entities)
                record_dict = result_dict.get('data')
                record_list = list()
                desc = result_dict.get('desc')
                if desc != '':
                    response_dict['desc'] = desc

                for record in record_dict.keys():
                    tmp_dict = {'content': record, 'recordId': int(record_dict.get(record))}
                    record_list.append(tmp_dict)

                response_dict['status'] = 'true'
                response_dict['data'] = record_list

            elif data_type == 'eq':
                parentId = jdata.get('parentId')
                for q in add_question:
                    entity['content'] = q
                    entity['parentRecordId'] = parentId
                    entities.append(entity)

                result_dict = insert_questions(data_type, appid, userid, entities)
                record_dict = result_dict.get('data')
                record_list = list()
                desc = result_dict.get('desc')
                if desc != '':
                    response_dict['desc'] = desc

                for record in record_dict.keys():
                    tmp_dict = {'content': record, 'recordId': int(record_dict.get(record))}
                    record_list.append(tmp_dict)

                response_dict['status'] = 'true'
                response_dict['data'] = record_list

        except Exception, e:
            response_dict['desc'] = str(e)
        return jsonify(response_dict)


@app.route('/deletequestion', methods=['GET', 'POST'])
def delete_question():
    if request.method == 'POST':
        response_dict = {'status': 'false'}
        try:
            jdata = request.json
            delete_questions = jdata.get('deleteValue')
            data_type = jdata.get('type')
            appid = jdata.get('appid')

            payload = {'op': 'delete',
                       'userRecordId': 8,
                       'appid': appid}

            if data_type == 'sq':
                payload['category'] = 'sq'
                payload['entities'] = delete_questions
                r = requests.post(DATABASE_URL, data=json.dumps(payload))
                jdata = r.json()
                if jdata.get('errno') != ERROR_SUCCESS:
                    response_dict['desc'] = '数据删除失败'
                else:
                    response_dict['status'] = 'true'
                    response_dict['desc'] = '数据删除成功'

            elif data_type == 'bq':
                payload['category'] = 'bq'
                payload['entities'] = delete_questions
                r = requests.post(DATABASE_URL, data=json.dumps(payload))
                jdata = r.json()
                if jdata.get('errno') != ERROR_SUCCESS:
                    response_dict['desc'] = '数据删除失败'
                else:
                    response_dict['status'] = 'true'
                    response_dict['desc'] = '数据删除成功'

            elif data_type == 'eq':
                eq_entities = list()
                lq_entities = list()
                for question in delete_questions:
                    if question['class'] == 'EQ' and question['editQ']:
                        eq_entities.append(question['editQ'])
                    else:
                        lq_entities.append(question['editQ'])

                if len(eq_entities):
                    payload['category'] = 'eq'
                    payload['entities'] = eq_entities
                    r = requests.post(DATABASE_URL, data=json.dumps(payload))
                    jdata = r.json()
                    if jdata.get('errno') != ERROR_SUCCESS:
                        response_dict['desc'] = '数据删除失败'
                        return jsonify(response_dict)
                    else:
                        response_dict['status'] = 'true'
                        response_dict['desc'] = '数据删除成功'

                if len(lq_entities):
                    payload['category'] = 'lq'
                    payload['entities'] = lq_entities
                    r = requests.post(DATABASE_URL, data=json.dumps(payload))
                    jdata = r.json()
                    if jdata.get('errno') != ERROR_SUCCESS:
                        response_dict['desc'] = '数据删除失败'
                    else:
                        response_dict['status'] = 'true'
                        response_dict['desc'] = '数据删除成功'

            print delete_questions, data_type
        except Exception, e:
            response_dict['desc'] = str(e)
        return jsonify(response_dict)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
